package cn.fl.system.controller;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjCstNpBscInfoService;
import cn.fl.project.service.IPrjPrdBscInfoService;
import cn.fl.system.condition.SysScoreIdxOptQueryCondition;
import cn.fl.system.condition.SysScoreIdxQueryCondition;
import cn.fl.system.condition.SysScoreRecQueryCondition;
import cn.fl.system.condition.SysScoreTmplQueryCondition;
import cn.fl.system.dto.SysScoreIdxOptDTO;
import cn.fl.system.dto.SysScoreTmplDTO;
import cn.fl.system.service.ISysScoreIdxOptService;
import cn.fl.system.service.ISysScoreIdxService;
import cn.fl.system.service.ISysScoreRecService;
import cn.fl.system.service.ISysScoreTmplService;
import cn.fl.system.vo.SysScoreIdxVO;
import cn.fl.system.vo.SysScoreRecVO;

/**
 * @Description: 评分记录表 控制层
 */
@Controller
@RequestMapping("/system/sysscorerec")
public class SysScoreRecController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(SysScoreRecController.class);

	/**
	 * SysScoreRec 服务层BEAN
	 */
	@Autowired
	private ISysScoreRecService sysScoreRecService;
	
	@Autowired
	private IPrjBscInfoService prjBscInfoService;
	
	@Autowired
	private IPrjCstNpBscInfoService prjCstNpBscInfoService;
	
	@Autowired
	private IPrjPrdBscInfoService prjPrdBscInfoService;
	@Autowired
	private ISysScoreTmplService sysScoreTmplService;
	
	@Autowired
	private ISysScoreIdxService sysScoreIdxService;
	
	@Autowired
	private ISysScoreIdxOptService sysScoreIdxOptService;
	/**
	 * 字典服务层BEAN
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		logger.info("加载SysScoreRec列表页面.");
		ModelAndView view = new ModelAndView("system/sysscorerec/list");
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		logger.info("加载SysScoreRec Modify页面.");
		ModelAndView view = new ModelAndView("system/sysscorerec/modify");
		view.addObject("id", id);
		return view;
	}
	

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(currentPage)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		SysScoreRecQueryCondition qc = new SysScoreRecQueryCondition();
		page.setCondition(qc);

		Pager pager = this.sysScoreRecService.searchListPage(page);
		List<SysScoreRecVO> list = (List<SysScoreRecVO>) pager.getResultList();
		ListPageVO<SysScoreRecVO> listPage = new ListPageVO<SysScoreRecVO>(list, pager.getTotalCount());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功");
		if(StringUtils.isEmpty(ids)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("删除主键参数不存在！");
			return result;
		}
		try {
			List<Long> idList = new ArrayList<>();
			List<String> idTempList = Arrays.asList(ids);
			for (String string : idTempList) {
				idList.add(Long.valueOf(string));
			}
			this.sysScoreRecService.removeById(idList);
			logger.debug("==remove==ids:" + ids);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("删除失败");
			logger.error("删除失败!", ex);
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "获取成功");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("主键参数不完整！");
			return result;
		}
		
		try {
			SysScoreRecVO vo = this.sysScoreRecService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("数据不存在！");
			}
			result.setData(vo);
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("获取数据失败！");
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
		try {
			SysScoreRecVO entity = new SysScoreRecVO();
			Long id = this.sysScoreRecService.add(entity);
			result.setData(id);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("新增失败!");
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,"修改成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("参数不完整！");
			return result;
		}
		try {
			SysScoreRecVO entity = new SysScoreRecVO();
			entity.setId(Long.valueOf(id));
			boolean success = this.sysScoreRecService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("修改失败！");
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("修改失败!");
			logger.error("修改失败!", ex);
		}
		return result;
	}
	
	/**
	 * 获取项目评分
	 */

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getPrjScore.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getPrjScore(HttpServletRequest request, HttpServletResponse response) {

		String id = request.getParameter("id");
//		List<SysScoreRecVO> list = this.sysScoreRecService.selectPrjScore(Long.parseLong(id));	
//
//
//		
//		for (SysScoreRecVO sysScoreRecVO : list) {
//			 getScore(sysScoreRecVO);
//		}
		List<SysScoreRecVO> list = this.sysScoreRecService.getScoreByPrjId(Long.parseLong(id));
		ListPageVO<SysScoreRecVO> listPage = new ListPageVO<SysScoreRecVO>(list, list.size());
		return listPage;
	}
	
	@RequestMapping(value = "/toGetPrjScore.do", method = { RequestMethod.GET, RequestMethod.POST })
	public Object toGetPrjScore(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		BaseLogUtils.info(logger, "toCheck", "加载项目信用分数.",CurrentThreadContext.getCurrentUserName());
		ModelAndView view = new ModelAndView("system/sysscorerec/prjScore");
view.addObject("id", id);
		return view;
	}
	/**
	 * 获取信用等级
	 */
	private String getCredLv(double value){
		String lv="超出配置范围";
		SysScoreTmplQueryCondition tqc= new SysScoreTmplQueryCondition();
		tqc.setTmplCd("creditrat");
		Pager pageT =new Pager();
		pageT.setCondition(tqc);;

		pageT=this.sysScoreTmplService.searchListPage(pageT);
		List<SysScoreTmplDTO> tmplList=(List<SysScoreTmplDTO>)pageT.getResultList();
		SysScoreIdxQueryCondition qc= new SysScoreIdxQueryCondition();
		if(tmplList==null || tmplList.size()!=1){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"creditrat模板获取异常");
		}
		
        qc.setTmplCd(tmplList.get(0).getId().toString());
    	List<SysScoreIdxVO> idxList=this.sysScoreIdxService.searchIdxList(qc);
		for (SysScoreIdxVO sysScoreIdxVO : idxList) {
			float coe=Float.parseFloat(sysScoreIdxVO.getIdxDesc());
			try {
				if(value>0){
					Pager page=new Pager();
					SysScoreIdxOptQueryCondition optqc=new SysScoreIdxOptQueryCondition();
					optqc.setTmplIdxId(sysScoreIdxVO.getId());
					page.setCondition(optqc);
				page=this.sysScoreIdxOptService.searchListPage(page);
				List<SysScoreIdxOptDTO> optList=	(List<SysScoreIdxOptDTO>) page.getResultList();
				for (SysScoreIdxOptDTO sysScoreIdxOptDTO : optList) {
					float maxval=Float.parseFloat(sysScoreIdxOptDTO.getMaxVal()) ;
					float mixval=Float.parseFloat(sysScoreIdxOptDTO.getMixVal()) ;
					float fvalue=(float)value;
					 if((sysScoreIdxOptDTO.getMaxOpr().equals("2") && maxval==fvalue) ||(maxval>fvalue)){
						 if((sysScoreIdxOptDTO.getMixOpr().equals("2") && mixval==fvalue) ||(mixval<fvalue)){
							 lv= sysScoreIdxOptDTO.getOptDesc();
						 } 
					 }
					
					
				}
			
				
			}

				
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				BaseLogUtils.info(logger, "getKvList", "信用等级获取失败.ERROR:"+e.getMessage(), CurrentThreadContext.getCurrentUserName());
			}
			
		}
		return lv;
	}
	/**
	 * 获取项目评分与违约率
	 */
	private SysScoreRecVO getScore(SysScoreRecVO vo){
		float score=0;
		SysScoreTmplQueryCondition tqc= new SysScoreTmplQueryCondition();
		tqc.setTmplCd("project");
		Pager pageT =new Pager();
		pageT.setCondition(tqc);;

		pageT=this.sysScoreTmplService.searchListPage(pageT);

		List<SysScoreTmplDTO> tmplList=(List<SysScoreTmplDTO>)pageT.getResultList();
		
		SysScoreIdxQueryCondition qc= new SysScoreIdxQueryCondition();
		if(tmplList==null || tmplList.size()!=1){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"PROJECT模板获取异常");
		}
		
        qc.setTmplCd(tmplList.get(0).getId().toString());
        score=tmplList.get(0).getCons();
		List<SysScoreIdxVO> idxList=this.sysScoreIdxService.searchIdxList(qc);
		for (SysScoreIdxVO sysScoreIdxVO : idxList) {
			float coe=Float.parseFloat(sysScoreIdxVO.getIdxDesc());
			try {
				String value=(String)invokeGet(vo,sysScoreIdxVO.getIdxCd());
				if(value!=null){
					Pager page=new Pager();
					SysScoreIdxOptQueryCondition optqc=new SysScoreIdxOptQueryCondition();
					optqc.setTmplIdxId(sysScoreIdxVO.getId());
					page.setCondition(optqc);
				page=this.sysScoreIdxOptService.searchListPage(page);
				List<SysScoreIdxOptDTO> optList=	(List<SysScoreIdxOptDTO>) page.getResultList();
			
				for (SysScoreIdxOptDTO sysScoreIdxOptDTO : optList) {
					
					if(sysScoreIdxOptDTO.getOptTypCd().equals("1") && sysScoreIdxOptDTO.getMaxVal().equals(value)){
						 score+= (sysScoreIdxOptDTO.getScrVal()*coe);
						 invokeSet(vo,sysScoreIdxVO.getIdxCd(),(sysScoreIdxOptDTO.getScrVal()*coe)+"");
						//	System.out.println(sysScoreIdxVO.getIdxCd()+":"+sysScoreIdxOptDTO.getScrVal()+"===="+score);	
					}
					if(sysScoreIdxOptDTO.getOptTypCd().equals("2")){
						float maxval=Float.parseFloat(sysScoreIdxOptDTO.getMaxVal().replaceAll("[^0-9.]", "")) ;
						float mixval=Float.parseFloat(sysScoreIdxOptDTO.getMixVal().replaceAll("[^0-9.]", "")) ;
						float fvalue=Float.parseFloat(value.replaceAll("[^0-9.]", "")) ;
						 if((sysScoreIdxOptDTO.getMaxOpr().equals("4") && maxval==fvalue) ||(maxval>fvalue)){
							 if((sysScoreIdxOptDTO.getMixOpr().equals("2") && mixval==fvalue) ||(mixval<fvalue)){
								 score+= (sysScoreIdxOptDTO.getScrVal()*coe);
								 invokeSet(vo,sysScoreIdxVO.getIdxCd(),(sysScoreIdxOptDTO.getScrVal()*coe)+"");
								//	System.out.println(sysScoreIdxVO.getIdxCd()+":"+sysScoreIdxOptDTO.getScrVal()+"===="+score);
							 } 
						 }
					}
					
				}
			
				
			}
				

			} catch (Exception e) {
				// TODO Auto-generated catch block
				BaseLogUtils.info(logger, "getKvList", "评分值获取失败.ERROR:"+e.getMessage(), CurrentThreadContext.getCurrentUserName());
			}
			
		}
		//计算P
		score=-1*score;
		double p=1/(Math.pow(Math.E, score)+1);
		vo.setCredSrc(p);
		vo.setCredLv(this.getCredLv(p));
		
		vo.setTotScr(score);
		return vo;
	}
	

	
    
    public static String getClassname(Object ob) throws Exception {
    	
    	return ob.getClass().getSimpleName();
    }
    public static Object invokeGet(Object owner, String pName) throws Exception {   
        
        Class ownerClass = owner.getClass();   
        Method[] ms=ownerClass.getMethods();
        Method method;
      //  Class[] argsClass = new Class[args.length];   
       int j=0;
        for (int i = 0;i<ms.length; i++) {   
          String methodnm=ms[i].getName();
          if(methodnm.toLowerCase().equals("get"+pName.toLowerCase())){  
  
        	  return ms[i].invoke(owner); 
          }
        }   

        return null;   
   }  
    
    public static Object invokeSet(Object owner, String pName,String cs) throws Exception {   
        
        Class ownerClass = owner.getClass();   
        Method[] ms=ownerClass.getMethods();
        Method method;
      //  Class[] argsClass = new Class[args.length];   
       int j=0;
        for (int i = 0;i<ms.length; i++) {   
          String methodnm=ms[i].getName();
          if(methodnm.toLowerCase().equals("set"+pName.toLowerCase()+'s')){  
  
        	  return ms[i].invoke(owner,cs); 
          }
        }   

        return null;   
   }  
}

